package server;

import java.io.*;
import java.net.Socket;

public class ResponseHandler implements Runnable {
    private final Socket clientSocket;
    private final ContactManager contactManager;

    public ResponseHandler(Socket clientSocket, ContactManager contactManager) {
        this.clientSocket = clientSocket;
        this.contactManager = contactManager;
    }

    @Override
    public void run() {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
             BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()))) {

            String request;
            while ((request = reader.readLine()) != null) {
                String[] parts = request.split(":");
                String response;

                switch (parts[0]) {
                    case "VIEW":
                        response = String.join(", ", contactManager.getContacts());
                        break;
                    case "ADD":
                        contactManager.addContact(parts[1], parts[2]);
                        response = "联系人添加成功";
                        break;
                    case "DELETE":
                        contactManager.deleteContact(parts[1]);
                        response = "联系人删除成功";
                        break;
                    case "UPDATE":
                        contactManager.updateContact(parts[1], parts[2]);
                        response = "联系人更新成功";
                        break;
                    default:
                        response = "无效请求";
                }

                writer.write(response + "\n");
                writer.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                clientSocket.close();
                System.out.println("客户端连接关闭: " + clientSocket.getInetAddress() + ":" + clientSocket.getPort());
            } catch (IOException e) {
                System.out.println("关闭客户端连接时出错: " + e.getMessage());
            }
        }
    }
}
